package dale.web.account;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import dale.web.core.security.IChangePassword;

/**
 * Used to service account requests.
 * 
 * @author Mularien
 */
@Controller
@RequestMapping("/account")
public class AccountController {
	
	@Autowired(required=false)
	private IChangePassword changePasswordDao;
	
	@RequestMapping(value="/changePassword",method=RequestMethod.GET)
	public void showChangePasswordPage() {		
	}
	
	@RequestMapping(value="/changePassword",method=RequestMethod.POST)
	public String submitChangePasswordPage(@RequestParam("password") String newPassword) {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		String username = principal.toString();
		if (principal instanceof UserDetails) {
		  username = ((UserDetails)principal).getUsername();
		}
		
		changePasswordDao.changePassword(username, newPassword);
		SecurityContextHolder.clearContext();
		
		return "redirect:/";
	}
	
}
